//
//  SelecteStoreVc.m
//  WGFGlobalHouses
//
//  Created by welldone on 15/5/21.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//

#import "SelecteStoreVc.h"
#import "BdTV.h"
#import "StoreSelecteCell.h"
#import "NodataCell.h"
#import "BrokerDM.h"
#import "StringTool.h"
#import "MBProgressHUD+MJ.h"
#import "SelecteStoreHeaderView.h"
#import "NSString+category.h"



@interface SelecteStoreVc ()

@property (nonatomic,strong)NodataCell *nodataCell;
@property (nonatomic,strong)NSArray *dataArray;
@property (nonatomic,strong)BrokerDM *dm;
@property (nonatomic,copy)StoreSelected returnBlock;
@property (strong, nonatomic) BdTV *titleView;
@property (copy, nonatomic) NSString *bufTitle;

@property (nonatomic,assign)NSInteger seletedRow;

@end

@implementation SelecteStoreVc
@synthesize nodataCell,dataArray,dm,selectedFlag,titleView,bufTitle;




-(instancetype)initWithBlock:(StoreSelected)block{
    
    self = [super init];
    if (self) {
        self.returnBlock = block;
    }
    return self;
}



-(void)setTitleViewStr:(NSString *)title{
    bufTitle = title;
    
    if (titleView) {
        [titleView setMianTitle:bufTitle];
    }
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self initView];
    
    
    [self refreshData];
}


-(void)initView{
    [super initView];
    
    titleView = [BdTV creatInstanceWithTitle:[StringTool isBlankString:bufTitle]?@"移动至":bufTitle];
    [titleView.backBtn setTag:11];
    [titleView.backBtn addTarget:self action:@selector(btnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [titleView.doneBtn setImage:nil forState:UIControlStateNormal];
    [titleView.doneBtn setAttributedTitle:[NSString makeLineStyle:@"完成" color:[UIColor whiteColor] fontSize:14] forState:UIControlStateNormal];
    titleView.doneBtn.tag = 100;
     [titleView.doneBtn addTarget:self action:@selector(btnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:titleView];

    
    self.tableView.rowHeight = [StoreSelecteCell getHight:nil withTableView:nil];
    self.tableView.estimatedRowHeight = [StoreSelecteCell getHight:nil withTableView:nil];
    
    dm = [[BrokerDM alloc]init];
    
}




-(void)refreshData{

    [nodataCell setState:nodataCellStateLoading];
    
    __weak typeof(self) bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        //不带缓存
        ResulteMod *mod = [dm refreshStoresDatawithStorecode:bself.storeCode];
       
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if(mod.resltState==ResultNetError){
            
                [bself.nodataCell setState:nodataCellStateNetError];
                
            }else if (mod.resltState==ResultFail){
        
                [bself.nodataCell setCodeErrorTip:mod.resultCode];
            }else{
            
                bself.dataArray = mod.dataMod;

                if (bself.dataArray.count == 0) {
                    [bself.nodataCell setState:nodataCellStateNodata];
                }
            }
            
            [bself.tableView reloadData];
            
        });
    });
}





-(void)btnOnClick:(UIButton *)sender{

    if (sender.tag==11) {
        [self.navigationController popViewControllerAnimated:YES];
    }else if (sender.tag==56){
        [self refreshData];
    }else if (sender.tag == 100){
       
        if (dataArray.count==0) {
            return;
        }
        
        if (self.vcType == BrokerQueryVcType) {
            
            if (self.returnBlock!=nil) {
                self.returnBlock([dataArray objectAtIndexedSubscript:self.seletedRow]);
            }
            
        }else if (self.vcType == BrokerAddVcType) {//添加
            
            if (self.returnBlock!=nil) {
                [self.navigationController popViewControllerAnimated:YES];
                self.returnBlock([dataArray objectAtIndexedSubscript:self.seletedRow]);
            }
            
        }else if (self.vcType == BrokerManageVcType)//单个移动
        {
            [self changeshopWithBrokerCellModel:self.model withNearByData:[dataArray objectAtIndexedSubscript:self.seletedRow]];
        }else if (self.vcType == BathMoveStore)//批量移动
        {
            [self bathchangeshopWithBorkeIds:self.borkerIds withNearByData:[dataArray objectAtIndexedSubscript:self.seletedRow]];
            
        }

    }
}



#pragma mark tableView delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (dataArray.count==0) {
        return tableView.frame.size.height;
    }
    
    return [StoreSelecteCell getHight:nil withTableView:nil];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (dataArray&&dataArray.count>0) {
        [self.tableView setScrollEnabled:YES];
        return self.dataArray.count;
    }else{
        [self.tableView setContentOffset:CGPointMake(0, 0)];
        [self.tableView setScrollEnabled:NO];
        return 1;
    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (dataArray.count==0) {
        if(!nodataCell){
            nodataCell = [[NodataCell alloc] initWithFrame:self.tableView.frame];
            [nodataCell setState:nodataCellStateLoading];
            [[nodataCell refreshBtn]setTag:56];
            [nodataCell.refreshBtn addTarget:self action:@selector(btnOnClick:) forControlEvents:UIControlEventTouchUpInside];
        }
        return nodataCell;
    }
    
    StoreSelecteCell *cell = [StoreSelecteCell cellWithTableView:tableView];
    NearbyCellData *cellData = [dataArray objectAtIndex:indexPath.row];
    

    [cell setIsChecked:[cellData.title isEqual:selectedFlag]];


    [cell setData:cellData];
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (dataArray.count==0) {
        return;
    }
    NearbyCellData *cellData = [dataArray objectAtIndex:indexPath.row];
    selectedFlag = cellData.title;
    [self.tableView reloadData];
    self.seletedRow = indexPath.row;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

#pragma mark 单个移动操作，提交数据
-(void)changeshopWithBrokerCellModel:(BorkerCellModel *)model withNearByData:(NearbyCellData *)data
{
    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
    
    __weak typeof(self)beself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
    ResulteMod *mod = [dm changeshopWithBorkerId:model.brokerId withShopCode:data.detail];
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:beself.view animated:YES];
            [beself.navigationController popViewControllerAnimated:YES];
            
              beself.returnBlock(nil);
            if (mod.resltState == ResultFail) {
                [MBProgressHUD showError:mod.resultTip];
            }else if (mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:@"网络错误"];
            }else
            {
                [MBProgressHUD showSuccess:@"操作成功"];
            }
           
        });
        
    });
}

#pragma mark 批量移动操作，提交数据
-(void)bathchangeshopWithBorkeIds:(NSString *)brokerIds withNearByData:(NearbyCellData *)data;
{
    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
    __weak typeof(self)bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        ResulteMod *mod =   [dm batchchangeshopWithBrokerIds:brokerIds WithShopCode:data.detail];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:bself.view animated:YES];
            if (bself.returnBlock != nil) {
            
                [bself.navigationController popViewControllerAnimated:YES];
                bself.returnBlock(nil);

            }
            
            
            if (mod.resltState == ResultFail) {
                [MBProgressHUD showError:mod.resultTip];
            }else if (mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:@"网络错误"];
            }else
            {
                [MBProgressHUD showSuccess:@"操作成功"];
            }
            
        });
    });

    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (self.dataArray!= nil && self.dataArray.count > 0)
    {
         return [SelecteStoreHeaderView getHeight];
    }
    
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
{
    if (self.dataArray!= nil && self.dataArray.count > 0){
        
        return [SelecteStoreHeaderView createView];
    }
        
    return nil;
}

@end
